<template>
  <div class="wrapper">
    <div id="app">
      <!-- 导航栏 -->
      <nav class="nav-bar">
        <div class="nav-left">
          <router-link to="/" class="nav-link">首页</router-link>
          <router-link to="/contact" class="nav-link">购物车</router-link>
          <router-link to="/about" class="nav-link">我的订单</router-link>
          <router-link to="/user" class="nav-link">我的</router-link>
        </div>
        <div class="nav-right">
          <template v-if="isLoggedIn">
            <div class="user-info">
              <span>{{ userInfo.name }}</span>
              <el-button type="text" @click="handleLogout">退出登录</el-button>
            </div>
          </template>
          <router-link to="/sign" class="nav-link" v-else>注册/登录</router-link>
        </div>
      </nav>

      <!-- 内容区 -->
      <div class="content">
        <!-- 加载状态显示 -->
        <div v-if="loading" style="text-align: center; padding: 20px;">加载中...</div>
        
        <!-- 错误信息显示 -->
        <div v-if="errorMessage && !loading" style="color: red; text-align: center; padding: 20px;">
          {{ errorMessage }}
        </div>
        
        <!-- 购物车表格 -->
        <el-table 
          v-if="tableData.length > 0 && !loading && !errorMessage"
          :data="tableData" 
          style="width: 100%" 
          border 
          stripe
        >
          <el-table-column prop="goodsid" label="商品id" width="180" />
          <el-table-column prop="goodsName" label="商品名称" width="180" />
          <el-table-column prop="price" label="单价" width="180" />
          
          <!-- 份数列（可编辑） -->
          <el-table-column label="份数" width="120">
            <template v-slot="scope">
              <el-input 
                v-model="scope.row.quantity" 
                type="number" 
                min="1" 
                size="small"
                @change="updateCartQuantity(scope.row)"
                :disabled="!isLoggedIn"
              />
            </template>
          </el-table-column>
          
          <!-- 总价列（自动计算） -->
          <el-table-column 
            label="总价" 
            width="180"
            :formatter="(row) => (row.price * row.quantity).toFixed(2)"
          />
          
          <!-- 图片列（添加容错处理） -->
          <el-table-column label="图片" width="120">
            <template v-slot="scope">
              <img 
                :src="scope.row.goodsPic ? getImageUrl(scope.row.goodsPic) : '/default.png'"  
                alt="商品图片" 
                style="max-width:80px;max-height:80px;"
                @error="handleImageError($event)"  
              />
            </template>
          </el-table-column>
          
          <!-- 操作列（购买/删除购物车记录） -->
          <el-table-column label="操作" width="200">
            <template v-slot="scope">
              <el-button 
                type="primary" 
                size="small"
                @click="handleBuy(scope.row)"
                :disabled="!isLoggedIn || scope.row.quantity > scope.row.remaining"
              >购买</el-button>
              <el-button 
                type="danger" 
                size="small"
                @click="handleDeleteCart(scope.row)"
                :disabled="!isLoggedIn"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 空购物车提示 -->
        <div v-if="tableData.length === 0 && !loading && !errorMessage" style="text-align: center; padding: 40px;">
          <p>您的购物车是空的~</p>
          <router-link to="/" class="nav-link">去逛逛</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElInput, ElButton, ElLoading } from 'element-plus';

export default {
  name: 'ShoppingCartView',
  components: {
    ElTable,
    ElTableColumn,
    ElInput,
    ElButton
  },
  data() {
    return {
      tableData: [], // 购物车数据
      isLoggedIn: false,
      userInfo: {},
      loginUserId: localStorage.getItem('userId') || null,
      loading: false,
      errorMessage: null
    };
  },
  mounted() {
    this.checkLoginStatus();
    if (!this.isLoggedIn) { 
      this.$router.push('/sign').catch(err => {
        console.warn('路由跳转失败:', err);
      });
      ElMessage.warning('请先登录查看购物车');
      return;
    }
    this.getShoppingCartList();
  },
  methods: {
    // 获取购物车列表
    async getShoppingCartList() {
      if (!this.loginUserId) return;
      
      this.loading = true;
      this.errorMessage = null;
      
      try {
        const response = await axios.get('http://127.0.0.1:8080/shoppingcart', {
          params: {
            userid: this.loginUserId
          }
        });
        
        if (response.status === 200 && Array.isArray(response.data)) {
          this.tableData = response.data.map(item => ({
            cartid: item.cartid,
            goodsid: item.goodsid,
            goodsName: item.goodsName || '未知商品',
            price: parseFloat(item.price) || 0,
            quantity: Number(item.quantity) || 1,
            goodsPic: item.goodsPic || '',
            remaining: Number(item.remaining) || 0
          }));
          console.log('购物车数据:', this.tableData);
        } else {
          this.errorMessage = '获取购物车失败：数据格式异常';
          ElMessage.error(this.errorMessage);
        }
      } catch (error) {
        this.errorMessage = '获取购物车失败：网络错误或服务器异常';
        ElMessage.error(this.errorMessage);
        console.error('购物车数据请求失败：', error);
      } finally {
        this.loading = false;
      }
    },
    
    // 生成图片URL
    getImageUrl(picName) {
      return `http://localhost:8080/images/${picName}`;
    },
    
    // 图片加载失败处理
    handleImageError(e) {
      e.target.src = '/default.png';
    },
    
    // 更新购物车数量
    async updateCartQuantity(row) {
      if (!this.loginUserId || !row.cartid) return;
      
      if (row.quantity < 1) {
        row.quantity = 1;
        ElMessage.warning('数量不能小于1');
        return;
      }
      if (row.quantity > row.remaining) {
        row.quantity = row.remaining;
        ElMessage.warning('数量不能超过库存');
        return;
      }
      
      try {
        await axios.put('http://127.0.0.1:8080/shoppingcart', null, {
          params: {
            cartid: row.cartid,
            userid: this.loginUserId,
            quantity: row.quantity,
            totalamount: row.price * row.quantity
          }
        });
        ElMessage.success('数量已更新');
      } catch (error) {
        ElMessage.error('更新数量失败，请重试');
        console.error('更新失败：', error);
        this.getShoppingCartList();
      }
    },
    
    // 处理购买操作（核心修改）
    handleBuy(row) {
      if (!this.isLoggedIn) {
        ElMessageBox.warning('请先登录再进行购买');
        this.$router.push('/sign');
        return;
      }
      
      if (row.quantity > row.remaining) {
        ElMessageBox.warning('商品库存不足，无法购买');
        return;
      }
      
      ElMessageBox.confirm(
        `确定购买 ${row.goodsName} x ${row.quantity} 件？总价：¥${(row.price * row.quantity).toFixed(2)}`,
        '购买确认',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        const loading = ElLoading.service({ text: '提交订单中...' });
        try {
          // 调用与商品详情页一致的购买接口
          const response = await axios.post(
            'http://127.0.0.1:8080/api/buys/purchases',
            {
              userId: parseInt(this.loginUserId),
              goodsId: row.goodsid,
              quantity: row.quantity,
              totalPrice: parseFloat((row.price * row.quantity).toFixed(2))
            },
            {
              headers: { 'Content-Type': 'application/json' }
            }
          );

          if (response.data.success) {
            // 提示订单状态为"待发货"
            ElMessage.success('购买成功！订单已创建，状态：待发货');
            // 从购物车删除
            await this.handleDeleteCart(row, false);
            // 跳转到"我的订单"页面
            this.$router.push('/about').catch(err => {
              console.warn('路由跳转失败:', err);
            });
          } else {
            ElMessage.error(response.data.message || '购买失败，请重试');
          }
        } catch (error) {
          console.error('下单失败：', error.response?.data || error.message);
          ElMessage.error(
            error.response?.data?.message || '系统异常，购买失败'
          );
        } finally {
          loading.close();
        }
      }).catch(() => {
        // 取消购买
      });
    },
    
    // 删除购物车记录
    async handleDeleteCart(row, showMessage = true) {
      if (!this.loginUserId || !row.cartid) return;
      
      try {
        await axios.delete('http://127.0.0.1:8080/shoppingcart', {
          params: {
            cartid: row.cartid,
            userid: this.loginUserId
          }
        });
        
        this.tableData = this.tableData.filter(item => item.cartid !== row.cartid);
        if (showMessage) {
          ElMessage.success('已从购物车移除');
        }
      } catch (error) {
        ElMessage.error('删除失败，请重试');
        console.error('删除购物车记录失败：', error);
      }
    },
    
    // 检查登录状态
    checkLoginStatus() {
      try {
        const storedUser = localStorage.getItem('userInfo');
        if (storedUser) {
          this.userInfo = JSON.parse(storedUser || '{}');
          this.isLoggedIn = true;
          this.loginUserId = this.userInfo.id;
        }
      } catch (err) {
        console.error('解析用户信息失败:', err);
        this.clearUserInfo();
      }
    },
    
    handleLogout() {
      try {
        this.clearUserInfo();
        this.isLoggedIn = false;
        this.userInfo = {};
        this.loginUserId = null;
        ElMessage.success('已退出登录');
        this.$router.push('/').catch(err => {
          console.warn('路由跳转失败:', err);
        });
      } catch (err) {
        console.error('退出登录出错:', err);
        this.isLoggedIn = false;
        this.loginUserId = null;
        ElMessage.success('已退出登录');
      }
    },
    
    clearUserInfo() {
      try {
        if (localStorage) {
          localStorage.removeItem('userInfo');
          localStorage.removeItem('userId');
        }
      } catch (err) {
        console.warn('清除本地存储失败:', err);
      }
    }
  },
  watch: {
    loginUserId(newVal) {
      if (newVal) {
        this.checkLoginStatus();
        this.getShoppingCartList();
      }
    }
  }
};
</script>

<style scoped>
.wrapper {
  padding: 20px;
}
.content {
  padding-top: 60px;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
.nav-left, .nav-right {
  display: flex;
  gap: 20px;
  align-items: center;
}
.nav-link {
  text-decoration: none;
  color: #333;
  padding: 5px 10px;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}
.nav-link.router-link-exact-active {
  color: #6b46c1;
  border-bottom-color: #6b46c1;
}

.el-table .cell img {
  border-radius: 4px;
  vertical-align: middle;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>